import { createStore } from 'vuex';
import { watch } from 'vue';
import { ADD_TODO_ITEM, REMOVE_TODO_ITEM, SET_ITEM_STATUS, INIT_TODO } from './types';

function getLoaclList() {
  let localList = JSON.parse(localStorage.getItem('todoListData'));
  if (!localList) {
    localList = {
      doing: [{ id: 1, content: '正在做' }],
      finished: [{ id: 3, content: '做完了' }]
    };
    reFlashLoacl(localList);
  }
  return localList;
}
function reFlashLoacl(curTodoList) {
  localStorage.setItem('todoListData', JSON.stringify(curTodoList));
}

export default createStore({
  state: {
    todoList: {}
  },
  mutations: {
    [INIT_TODO](state) {
      state.todoList = getLoaclList();
      watch(state.todoList, () => {
        reFlashLoacl(state.todoList);
      });
    },
    [ADD_TODO_ITEM](state, newTodo, aim = 'doing') {
      state.todoList[aim] = [newTodo, ...state.todoList[aim]];
    },
    [REMOVE_TODO_ITEM](state, payload) {
      const { curStatus, id } = payload;
      const aimArr = state.todoList[curStatus];
      for (let i = 0; i < aimArr.length; i++) {
        if (aimArr[i].id === id) {
          aimArr.splice(i, 1);
        }
      }
    },
    [SET_ITEM_STATUS](state, payload) {
      const { curStatus, id } = payload;
      const fromStatus = curStatus,
        toStatus = curStatus === 'doing' ? 'finished' : 'doing';
      const from = state.todoList[fromStatus];
      const to = state.todoList[toStatus];

      for (let i = 0; i < from.length; i++) {
        if (from[i].id === id) {
          to.push(from[i]);
          from.splice(i, 1);
        }
      }
    }
  },
  actions: {
    [SET_ITEM_STATUS]({ commit, state }, { curStatus, id }) {
      commit('SET_ITEM_STATUS', { curStatus, id });
    }
  }
});
